/*
 * @Description:本文件实现pub功能处理
 * @Author: 听风
 * @Date: 2021-02-03 21:05:33
 */
const Ora = require('ora');
const { copyPathOnRoot, copyFileOnRoot, downloadGitFile } = require('../uitls/fs');
const { name: appName } = require('../project');

// 下载SSL证书
const downloadSSL = (type, { ssl = [] }, spinner) => {
  if (type !== 'fe') return;
  const sslLen = ssl.length;
  if (!sslLen) {
    return;
  }
  spinner.text = '下载ssl证书……';
  if (sslLen > 1) {
    // 分开的路径, 下载到当前项目路径ssl
    ssl.forEach(s => {
      copyFileOnRoot(s, '/ssl');
    });
  } else {
    // 同一目录
    copyPathOnRoot(ssl[0], '/ssl');
  }
  spinner.text = '下载ssl证书完成';
};

// 创建dockerfile
const createDockerfile = async (type, options, spinner) => {
  // 配置项处理
  const { port, ssl = [], registry = 'https://registry.npm.taobao.org' } = options;
  const hasSSL = ssl.length > 0;

  // 下载ssl文件
  hasSSL && downloadSSL(type, options, spinner);

  // 渲染模板
  const meta = {
    appName,
    port,
    ssl: hasSSL ? 'COPY ./ssl /etc/ssl' : '',
    registry,
  };

  // 下载dockerfile
  await downloadGitFile(`${type}-dockerfile`, '/', 'dockerfile', {
    spinner,
    meta,
    isCover: options.yes,
  });
};

// 创建启动文件
const createStartBash = async (
  type,
  { port, ssl, yes, registry = 'https://registry.npm.taobao.org' },
  spinner
) => {
  const meta = {
    appName,
    port,
    portn: ssl ? 443 : 80,
    registry,
  };
  await downloadGitFile(`${type}-start`, '/', 'start.sh', { spinner, meta, isCover: yes });
};

// 创建nginx配置文件
const createNginxConf = async (type, { ssl, domain = '', yes }, spinner) => {
  if (type !== 'fe') return;
  await downloadGitFile(`nginx${ssl ? 'ssl' : ''}-conf`, '/', 'default.conf', {
    spinner,
    isCover: yes,
    meta: { domain: domain.startsWith('www.') ? domain : `www.${domain}` },
  });
};

// 核心处理方法
const action = async (type, options) => {
  const spinner = Ora('正在载入...').start();
  const params = [type, options, spinner];
  await createStartBash(...params);
  await createDockerfile(...params);
  await createNginxConf(...params);
  spinner.succeed('载入完成');
};

module.exports = action;
